package com.youxin.qiniu;

import cn.hutool.extra.spring.SpringUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.youxin.base.BaseResultCode;
import com.youxin.exception.SystemException;
import com.youxin.utils.SpringUtils;

public class QiniuUtil {

    public static void upload(byte[] bytes,String key){
        key = "file/download/" + key;
        QiniuProperties qiniuProperties = SpringUtils.getBean(QiniuProperties.class);
        Auth auth = SpringUtils.getBean(Auth.class);
        UploadManager uploadManager = SpringUtils.getBean(UploadManager.class);
        if(qiniuProperties == null || auth == null || uploadManager == null){
            throw new SystemException(BaseResultCode.COMMON_FAIL,"配置有误");
        }
        String upToken = auth.uploadToken(qiniuProperties.getBucket());
        try {
            Response response =  uploadManager.put(bytes, key, upToken);
        }catch (QiniuException ex ){
            Response r = ex.response;
            throw new SystemException(BaseResultCode.COMMON_FAIL,r.toString());
        }
    }
}
